package spring.distributed.lock.samples.controller;

import cn.fang2chen.distributed.lock.spring.DistributedLockAutoConfinguration;
import cn.fang2chen.distributed.lock.spring.MutexFactory;
import cn.fang2chen.java.distributed.lock.framework.RemoteLockParam;
import cn.fang2chen.java.distributed.lock.framework.RemoteLockSynchronizer;
import cn.fang2chen.java.distributed.lock.framework.impl.DistributedMutex;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Import;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * Title: MutexTestController
 *
 * @author dcmini chen
 * @since 1.0.0
 */
@RestController
@RequestMapping("/mutex")
@Slf4j
public class MutexTestController {

    @Autowired
    private MutexFactory mutexFactory;

    private static final String operatorId = "MutexTestController";

    @RequestMapping(path = "/acquire", method = RequestMethod.GET)
    public String acquireLock(@RequestParam("lockPath") String lockPath) {

        DistributedMutex distributedMutex
                = mutexFactory.tryGetIfNullCreate(new RemoteLockParam(lockPath, operatorId, 50000));

        distributedMutex.lock();
        log.info(Thread.currentThread().getName() + " 获取到锁： " + lockPath);

        log.info(Thread.currentThread().getName() + " 暂停 10s： "  + lockPath);
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        log.info(Thread.currentThread().getName() + " 起来了 ： " + lockPath);
        distributedMutex.unlock();
        log.info(Thread.currentThread().getName() + " 释放锁 ： " + lockPath);
        return "success";
    }







}
